import 'package:cashbook/custom/KeyEvent.dart';
import 'package:cashbook/custom/MyKeyboard.dart';
import 'package:cashbook/model/Accounts.dart';
import 'package:cashbook/model/eventbus_bean.dart';
import 'package:cashbook/utils/Commons.dart';
import 'package:cashbook/utils/UsNumberTextInputFormatter.dart';
import 'package:cashbook/utils/manager.dart';
import 'package:cashbook/utils/time_util.dart';
import 'package:cashbook/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';

class AddAccountsPage extends StatefulWidget {
  String title;

  AddAccountsPage({Key key, this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return AddAccountsState();
  }
}

class AddAccountsState extends State<AddAccountsPage> {
  bool currentSelect = true;
  List<String> lists = List();
  List<String> lists_cast = List();
  List<String> lists_income = List();
  bool showKeyB = false;
  var remark = TextEditingController();
  FocusNode _focusNode = FocusNode();
  var curVal = '0';
  var dateStr = '今天';

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      resizeToAvoidBottomPadding: true, //输入框抵住键盘
      appBar: AppBar(
        title: Text(this.widget.title),
        centerTitle: true,
      ),
      body: Container(
        padding: EdgeInsets.only(left: 5, right: 5),
        child: Column(
          children: <Widget>[
            Container(
              alignment: Alignment.center,
              margin: const EdgeInsets.only(bottom: 4, top: 5),
              height: 40,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  GestureDetector(
                    onTap: () {
                      changeSelectAction();
                    },
                    child: Container(
                      width: 100,
                      decoration: BoxDecoration(
                          border: Border.all(
                            width: 1,
                            color: Colors.blue,
                          ),
                          borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(5.0),
                              bottomLeft: Radius.circular(5))),
                      child: Container(
                        width: double.infinity,
                        alignment: Alignment.center,
                        height: double.infinity,
                        color: currentSelect ? Colors.blue : null,
                        child: Text(
                          '支出',
                          style: TextStyle(
                              color:
                                  currentSelect ? Colors.white : Colors.blue),
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      changeSelectAction();
                    },
                    child: Container(
                      width: 100,
                      decoration: BoxDecoration(
                          border: Border.all(
                            width: 1,
                            color: Colors.blue,
                          ),
                          borderRadius: BorderRadius.only(
                              topRight: Radius.circular(5.0),
                              bottomRight: Radius.circular(5))),
                      child: Container(
                        width: double.infinity,
                        alignment: Alignment.center,
                        height: double.infinity,
                        color: currentSelect ? null : Colors.blue,
                        child: Text(
                          '收入',
                          style: TextStyle(
                              color:
                                  currentSelect ? Colors.blue : Colors.white),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
                child: GridView.builder(
                    gridDelegate: new SliverGridDelegateWithMaxCrossAxisExtent(
                      //SliverGridDelegateWithFixedCrossAxisCount可以直接指定每行（列）显示多少个Item   SliverGridDelegateWithMaxCrossAxisExtent会根据GridView的宽度和你设置的每个的宽度来自动计算没行显示多少个Item
                      crossAxisSpacing: 10.0,
                      mainAxisSpacing: 10.0,
                      maxCrossAxisExtent: 50.0,
                    ),
                    itemCount: lists.length,
                    itemBuilder: (BuildContext context, int index) {
                      return GestureDetector(
                          onTap: () {
                            itemClickEvent(index, lists[index]);
                          },
                          child: CircleAvatar(
                            child: Center(
                              child: Text(lists[index]),
                            ),
                          ));
                    })),
//            Divider(
//              height: 1,
//              color: Colors.black26,
//            ),
//            Container(
//              height: 45,
//              color: Colors.white,
//              child: Row(
//                children: <Widget>[
//                  Container(
//                    margin: const EdgeInsets.only(left: 10),
//                    child: Text('备注：'),
//                  ),
//                  Expanded(
//                    flex: 1,
//                    child: TextField(
//                      focusNode: _focusNode,
//                      controller: remark,
//                      maxLines: 1,
//                      decoration: InputDecoration(
//                          hintText: '写点撒', border: InputBorder.none),
//                    ),
//                  ),
//                  Expanded(
//                    flex: 1,
//                    child: GestureDetector(
//                      onTap: () {
//                        Future.delayed(Duration(milliseconds: 80), () {
//                          setState(() {
//                            showKeyB = true;
//                            print('======${showKeyB}');
//                          });
//                        });
//                        _focusNode.unfocus();
//                      },
//                      child: Container(
//                        height: double.infinity,
//                        color: Colors.white,
//                        alignment: Alignment.centerRight,
//                        padding: const EdgeInsets.only(right: 10),
//                        child: Text('￥${curVal}'),
//                      ),
//                    ),
//                  )
//                ],
//              ),
//            ),
//            showKeyB == true
//                ? MyKeyboard((v) {
//                    print('======>' + v.key);
//                    switchVal(v.key, v);
//                  })
//                : Container(),
          ],
        ),
      ),
    );
  }

  void itemClickEvent(int index, String v) {
    List<TextInputFormatter> formatters = List();
    formatters.add(UsNumberTextInputFormatter());
    var priceC = TextEditingController();
    var remarkC = TextEditingController();
    Toast.toast(context, '${v}');
    setState(() {
      showKeyB = true;
    });
    this.dateStr = '今天';
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context, state) {
            return AlertDialog(
              content: Container(
                height: 145,
                child: Column(
                  children: <Widget>[
                    Text('你选中 ：${v}'),
                    TextField(
                      keyboardType: TextInputType.number,
                      inputFormatters: formatters,
                      controller: priceC,
                      decoration: InputDecoration(hintText: '金额'),
                    ),
                    TextField(
                      controller: remarkC,
                      decoration: InputDecoration(hintText: '备注'),
                    ),
                    Container(
                      width: double.infinity,
                      margin: EdgeInsets.only(top: 12, bottom: 0),
                      child: GestureDetector(
                        child: Container(
                          width: double.infinity,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Text('日期 ：'),
                              Expanded(
                                flex: 1,
                                child: Text('${dateStr}'),
                              )
                            ],
                          ),
                        ),
                        onTap: () {
                          DatePicker.showDatePicker(context,
                              showTitleActions: true, onChanged: (date) {
                            print('变更：${date}');
                          }, onConfirm: (date) {
                            print('选择：${date}');
                            state(() {
                              dateStr =
                                  '${date.year}/${date.month}/${date.day}';
                            });
                          },
                              currentTime: DateTime.now(),
                              locale: LocaleType.zh);
                        },
                      ),
                    )
                  ],
                ),
              ),
              actions: <Widget>[
                FlatButton(
                    onPressed: () {
                      Navigator.of(context).pop('-1');
                      this.dateStr = '今天';
                    },
                    child: Text('取消')),
                FlatButton(
                    onPressed: () {
                      if (priceC.text != null &&
                          priceC.text.length > 0 &&
                          double.parse(priceC.text.trim()) >= 0) {
                        if ('今天' == dateStr) {
                          var date = DateTime.now();
                          dateStr = '${date.year}/${date.month}/${date.day}';
                        }

                        Navigator.of(context).pop('1');
                        addAccountAction(v, priceC.text.trim().toString(),
                            remarkC.text.trim().toString(), dateStr);
                      } else {
                        Toast.toast(context, '金额必须大于0');
                      }
                    },
                    child: Text('确定')),
              ],
            );
          });
        });
  }

  @override
  void initState() {
    super.initState();
    lists_income.add('餐饮');
    lists_income.add('购物');
    lists_income.add('日用');
    lists_income.add('交通');
    lists_income.add('蔬菜');
    lists_income.add('水果');
    lists_income.add('零食');
    lists_income.add('运动');
    lists_income.add('娱乐');
    lists_income.add('通信');
    lists_income.add('服饰');
    lists_income.add('美容');
    lists_income.add('住房');
    lists_income.add('社交');
    lists_income.add('旅行');
    lists_income.add('烟酒');
    lists_income.add('汽车');

    lists_cast.add('工资');
    lists_cast.add('兼职');
    lists_cast.add('理财');
    lists_cast.add('其他');

    lists.addAll(lists_income);
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        setState(() {
          showKeyB = false;
        });
      }
    });
  }

  void changeSelectAction() {
    setState(() {
      currentSelect = !currentSelect;
      if (currentSelect) {
        this.lists.clear();
        this.lists.addAll(lists_income);
      } else {
        this.lists.clear();
        this.lists.addAll(lists_cast);
      }
    });
  }

  void switchVal(String k, KeyEvent v) {
    switch (k) {
      case 'miss':
        setState(() {
          this.showKeyB = false;
        });
        break;
      case '1':
        double d = double.parse(this.curVal);
        if (d == 0 && !this.curVal.contains('.')) {
          this.curVal = '${1}';
        } else {
          this.curVal = this.curVal + '${1}';
        }
        break;
      case '2':
        double d = double.parse(this.curVal);
        if (d == 0 && !this.curVal.contains('.')) {
          this.curVal = '${2}';
        } else {
          this.curVal = this.curVal + '${2}';
        }
        break;
      case '3':
        double d = double.parse(this.curVal);
        if (d == 0 && !this.curVal.contains('.')) {
          this.curVal = '${3}';
        } else {
          this.curVal = this.curVal + '${3}';
        }
        break;
      case '4':
        double d = double.parse(this.curVal);
        if (d == 0 && !this.curVal.contains('.')) {
          this.curVal = '${4}';
        } else {
          this.curVal = this.curVal + '${4}';
        }
        break;
      case '5':
        double d = double.parse(this.curVal);
        if (d == 0 && !this.curVal.contains('.')) {
          this.curVal = '${5}';
        } else {
          this.curVal = this.curVal + '${5}';
        }
        break;
      case '6':
        double d = double.parse(this.curVal);
        if (d == 0 && !this.curVal.contains('.')) {
          this.curVal = '${6}';
        } else {
          this.curVal = this.curVal + '${6}';
        }
        break;
      case '7':
        double d = double.parse(this.curVal);
        if (d == 0 && !this.curVal.contains('.')) {
          this.curVal = '${7}';
        } else {
          this.curVal = this.curVal + '${7}';
        }
        break;
      case '8':
        double d = double.parse(this.curVal);
        if (d == 0 && !this.curVal.contains('.')) {
          this.curVal = '${8}';
        } else {
          this.curVal = this.curVal + '${8}';
        }
        break;
      case '9':
        double d = double.parse(this.curVal);
        if (d == 0 && !this.curVal.contains('.')) {
          this.curVal = '${9}';
        } else {
          this.curVal = this.curVal + '${9}';
        }
        break;
      case '0':
        double d = double.parse(this.curVal);
        if (d == 0 && !this.curVal.contains('.')) {
          this.curVal = '${0}';
        } else {
          this.curVal = this.curVal + '${0}';
        }
        break;
      case '.':
        var ctmp = this.curVal.contains('.');
        if (!ctmp) {
          this.curVal = this.curVal + '.';
        }
        break;
      case 'del':
        if (this.curVal.length > 1) {
          this.curVal = this.curVal.substring(0, this.curVal.length - 1);
        } else {
          this.curVal = '0';
        }

        break;
      case 'commit':
        //_addAccountAction("", curVal, remark.text.toString(), v.dataStr);
        break;
    }
    setState(() {
      this.curVal;
    });
  }

  void addAccountAction(
      String title, String curVal, String remark, String data) {
    Accounts accounts = Accounts();
    accounts.uUUID = Manager.instance.loginUser.userUuid; //用户表示
    accounts.title = title;
    accounts.createTime = TimeUtil.getTimestampFromData(data);
    accounts.createYearAndMouth = data.substring(0, data.lastIndexOf('/'));
    accounts.type = currentSelect ? 'ZC' : 'SR';
    accounts.remark = remark;
    accounts.money = curVal;

    insertAccounts(accounts);
    print("===" + accounts.toString());
  }

  void getDataAction(String val) {}

  void insertAccounts(Accounts accounts) async {
    int flag = await AccountsProvider().insert(accounts);
    if (flag > -1) {
      Toast.toast(context, '添加成功');
      var bean = EventBusBean(Commons.REFRESH_ACCOUNTS, "");
      Manager.instance.eventBus.fire(bean);
      Navigator.pop(context);
    } else {
      Toast.toast(context, '添加失败');
    }
  }

  @override
  void dispose() {}
}
